import { createRouter, createWebHistory } from 'vue-router'
import { useCounterStore } from '@/stores/counter'
import Home from '../views/Home.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
      redirect: '/order',
      children: [
        /* 订单管理 */
        {
          path: '/order',
          name: 'Order',
          component: () => import('../views/order/Order.vue')
        },
        /**药品管理 */
        {
          path: '/dish',
          name: 'Dish',
          component: () => import('../views/dish/Dish.vue')
        },
        /* 套餐管理 */
        {
          path: '/setmeal',
          name: 'Setmeal',
          component: () => import('../views/setmeal/Setmeal.vue')
        },
        /* 分类管理 */
        {
          path: '/category',
          name: 'Category',
          component: () => import('../views/category/Category.vue')
        },
        /* 员工管理 */
        {
          path: '/employee',
          name: 'Employee',
          component: () => import('../views/employee/Employee.vue')
        },
        /* 用户管理 */
        {
          path: '/user',
          name: 'User',
          component: () => import('../views/user/User.vue')
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue')
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue')
    }
  ]
})
1
// 所有的路由在真正被访问到之前(解析渲染对应组件页面前),都会先经过全局前置守卫
// 只有全局前置守卫放行了,才会到达对应的页面

// 全局前置导航守卫
// to:到哪里去,到哪去的完整路由信息对象(路径，参数)
// from:从哪里来, 从哪来的完整路由信息对象(路径，参数)
// next:是否放行
// (1) next() 直接放行,放行到to要去的路径
// (2) next(路径) 进行拦截,拦截到next里面配置的路径

// 定义一个数组,专门用于用户存放所有非权限访问的页面
const authUrls = ['/login']
router.beforeEach((to, from, next) => {
  // console.log(to, from, next)
  // 看to.path是否在authUrls中出现过
  if (authUrls.includes(to.path)) {
    // 非权限页面,直接放行
    console.log('非权限页面,直接放行')
    next()
    return
  }
  // 是权限页面,需要判断token
  const token = useCounterStore().token
  if (token) {
    console.log('放行')
    next()
  } else {
    console.log('拦截')
    next('/login')
  }
})

export default router

